package com.org.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.org.bean.system.UserInfo;
import com.org.bean.system.UserTempInfo;
import com.org.service.UserService;
import com.org.service.UserTempService;

@Controller
public class LoginAction {

	/**
	 * 用户登录验证
	 */
	@Autowired
	private UserService userService;
	@Autowired
	private UserTempService userTempService;
	private Iterator<String> iter;
	private List<String> list;

	private Map<String, Object> status(List<UserInfo> userInfo, String password) {
		// TODO Auto-generated method stub
		Map<String, Object> m = new HashMap<String, Object>();
		if (userInfo.size() == 0) {
			m.put("statusCode", 0);
			m.put("msg", "用户名出错");

		} else if (userInfo.get(0).getPassword().equals(password)) {
			m.put("statusCode", 1);
			m.put("msg", "登录成功");
		} else {
			m.put("statusCode", 0);
			m.put("msg", "用户密码错误");
		}
		return m;
	}

	@SuppressWarnings("unused")
	@RequestMapping("/login")
	public @ResponseBody Map<String, Object> getUserInfo(
			@RequestBody Map<String, Object> userMap) throws ParseException {
		iter = userMap.keySet().iterator(); // 获取Map集合的key值
		list = new ArrayList<String>();
		while (iter.hasNext()) {
			list.add(iter.next());
		}
		boolean result1,result2;
		String password;
		UserInfo userInfo = new UserInfo();
		userInfo.setUserName((String) userMap.get(list.get(0)));
		userInfo.setPassword((String) userMap.get(list.get(1)));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 将字符串转换为DATE类型
		Date date = sdf.parse((String) userMap.get(list.get(2)));
		userInfo.setLastLogin(date);
		password = userInfo.getPassword();
		List<UserInfo> userInfos = new ArrayList<UserInfo>();
		userInfos = userService.login(userInfo.getUserName());
		if (userInfos.size() != 0) {
			userInfo.setUserId(userInfos.get(0).getUserId());
			result1 = userService.updateUser(userInfo);
			UserTempInfo userTempInfo=new UserTempInfo();
			userTempInfo.setUserName((String) userMap.get(list.get(0)));
			result2=userTempService.addUser(userTempInfo);
		}
		
		return status(userInfos, password);
	}
}
